<template>
  <div>
    <Drawer
      width="50%"
      :title="title"
      placement="right"
      v-model:visible="visible"
      :footer-style="{ textAlign: 'right' }"
      @close="onClose"
    >
      <template #closeIcon>
        <arrow-left-outlined />
      </template>
      <Form ref="formRef" :model="formState" name="basic" :rules="title == '规则详情' ? {} : rules" :selfUpdate="false">
        <Card>
          <Row :gutter="16">
            <Col span="12">
              <FormItem label="规则名称" name="ruleName">
                <template v-if="title == '规则详情'">{{ formState.ruleName }}</template>
                <Input v-if="!(title == '规则详情')" v-model:value="formState.ruleName" placeholder="请输入"></Input>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="规则描述">
                <template v-if="title == '规则详情'">{{ formState.ruleDesc }}</template>
                <Textarea
                  v-if="!(title == '规则详情')"
                  v-model:value="formState.ruleDesc"
                  :rows="4"
                  placeholder="请输入"
                ></Textarea>
              </FormItem>
            </Col>
          </Row>
          <Row :gutter="16">
            <Col span="12">
              <FormItem label="所属链路" name="routeLink">
                <template v-if="title !== '创建规则'">{{ routeLinkLabel }}</template>
                <Select
                  v-if="title == '创建规则'"
                  v-model:value="formState.routeLink"
                  label-in-value
                  :options="routeLinkList"
                  placeholder="请选择"
                >
                </Select>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="规则权重" name="weight">
                <template v-if="title == '规则详情'">{{ formState.weight }}</template>
                <Input v-if="!(title == '规则详情')" v-model:value="formState.weight" placeholder="请输入"></Input>
              </FormItem>
            </Col>
          </Row>
          <Row :gutter="16">
            <Col span="12">
              <FormItem label="优先等级" name="priority">
                <template v-if="title == '规则详情'">{{ formState.priority }}</template>
                <Input v-if="!(title == '规则详情')" v-model:value="formState.priority" placeholder="请输入"></Input>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="规则生效关系" name="ruleRelationship">
                <template v-if="title == '规则详情'">{{ formState.ruleRelationship == 'and' ? '与' : '或' }}</template>
                <RadioGroup v-if="!(title == '规则详情')" v-model:value="formState.ruleRelationship">
                  <Tooltip title="同时满足所有规则" placement="topLeft">
                    <Radio :style="radioStyle" value="and">与</Radio>
                  </Tooltip>
                  <Tooltip title="满足任意规则" placement="bottomLeft">
                    <Radio :style="radioStyle" value="or">或</Radio>
                  </Tooltip>
                </RadioGroup>
              </FormItem>
            </Col>
          </Row>
          <Row :gutter="16">
            <Col span="12">
              <FormItem label="是否启用">
                <template v-if="title == '规则详情'">{{ formState.checked == true ? '启用' : '停用' }}</template>
                <Switch
                  v-if="!(title == '规则详情')"
                  v-model:checked="formState.checked"
                  checkedChildren="启用"
                  unCheckedChildren="停用"
                ></Switch>
              </FormItem>
            </Col>
          </Row>
        </Card>
        <br />
        <Card>
          <template v-if="!(title == '规则详情')">
            <div class="btn-wrapper">
              <Button class="editable-add-btn" style="margin-bottom: 8px" type="dashed" @click="handleAdd">
                <template #icon><PlusOutlined /></template>新增匹配
              </Button>
            </div>
          </template>
          <Table
            bordered
            :data-source="dataSource"
            :columns="title == '规则详情' ? drawerColumns2 : drawerColumns"
            :pagination="false"
          >
            <template #bodyCell="{ column, text, record }">
              <template v-if="column.dataIndex == 'keyWord'">
                <div>
                  <Select
                    v-if="editableData[record.id]"
                    v-model:value="editableData[record.id][column.dataIndex]"
                    :options="keyList"
                    style="margin: -5px 0; width: 150px"
                  ></Select>
                  <template v-else>
                    {{ text }}
                  </template>
                </div>
              </template>
              <template v-else-if="column.dataIndex == 'matchType'">
                <div>
                  <Select
                    v-if="editableData[record.id]"
                    v-model:value="editableData[record.id][column.dataIndex]"
                    :options="matchTypeList"
                    style="margin: -5px 0; width: 150px"
                  ></Select>
                  <template v-else>
                    {{ computeMatchType(record.matchType) }}
                  </template>
                </div>
              </template>
              <template v-else-if="column.dataIndex === 'valueWord'">
                <Input
                  v-if="editableData[record.id]"
                  v-model:value="editableData[record.id][column.dataIndex]"
                  style="margin: -5px 0; width: 150px"
                  @change="inputChange"
                ></Input>
                <template v-else>
                  {{ text }}
                </template>
              </template>
              <template v-else-if="column.dataIndex === 'action'">
                <div class="editable-row-operations">
                  <span v-if="editableData[record.id]">
                    <TypographyLink @click="save(record.id)" :disabled="!enableSave">保存</TypographyLink>
                  </span>
                  <span v-else>
                    <a @click="edit(record.id)">编辑</a>
                    <Divider type="vertical" />
                    <Popconfirm title="确定删除吗?" @confirm="onDelete(record.id)" ok-text="确定" cancel-text="取消">
                      <a>删除</a>
                    </Popconfirm>
                  </span>
                </div>
              </template>
            </template>
          </Table>
        </Card>
      </Form>
      <template #footer>
        <template v-if="!(title == '规则详情')">
          <Button style="margin-right: 8px" type="primary" @click="submit">提交</Button>
          <Button @click="onClose">取消</Button>
        </template>
      </template>
    </Drawer>
  </div>
</template>
<script lang="ts" setup>
import {
  Drawer,
  Card,
  Row,
  Col,
  Form,
  FormItem,
  Button,
  Table,
  Textarea,
  Input,
  Select,
  Radio,
  Tooltip,
  RadioGroup,
  Switch,
  Popconfirm,
  TypographyLink,
  Divider,
  message,
} from 'ant-design-vue';
import { ArrowLeftOutlined, PlusOutlined } from '@ant-design/icons-vue';
import { computed, reactive, Ref, ref } from 'vue';
import {
  createRule,
  editRule,
  getRouteLink,
  getRuleDetail,
} from '/@/api/upgrade-center/grayscale/ruleManagement/ruleManagement';
import { cloneDeep } from 'lodash-es';
import { matchTable } from '/@/api/upgrade-center/grayscale/ruleManagement/model/ruleManagementModel';
import { Rule } from 'ant-design-vue/lib/form';
import { drawerColumns, drawerColumns2 } from '/@/views/upgrade-center/grayscale/ruleManagement/data';
// 校验
const formRef = ref();
const checkWeight = async (_rule: Rule, value: number) => {
  if (!Number(value) || !Number.isInteger(Number(value)) || Number(value) < 0 || Number(value) > 100) {
    return Promise.reject(new Error('请输入0~100的整数'));
  }
};
const checkPriority = async (_rule: Rule, value: number) => {
  if (!Number(value) || !Number.isInteger(Number(value)) || Number(value) < 1 || Number(value) > 999) {
    return Promise.reject(new Error('请输入1~999的整数'));
  }
};

const rules: Record<string, Rule[]> = {
  ruleName: [{ required: true, message: '规则名称不能为空', trigger: 'change' }],
  routeLink: [{ required: true, message: '所属链路不能为空', trigger: 'change' }],
  weight: [{ required: true, validator: checkWeight, trigger: 'change' }],
  priority: [{ required: true, validator: checkPriority, trigger: 'change' }],
  ruleRelationship: [{ required: true, message: '规则生效关系不能为空', trigger: 'change' }],
};
const handleValidate = async () => {
  return formRef.value.validate();
};

const keyList = ref([
  {
    label: 'tenant',
    value: 'tenant',
  },
  {
    label: 'userid',
    value: 'userid',
  },
  {
    label: 'appid',
    value: 'appid',
  },
]);
const matchTypeList = ref([
  {
    label: '精准匹配',
    value: 'exact',
  },
  {
    label: '正则匹配 ',
    value: 'regex',
  },
  {
    label: '包含',
    value: 'contains',
  },
]);
interface DataItem {
  id: string;
  keyWord: string;
  matchType: string;
  valueWord: string;
  key: string;
}
const dataSource: Ref<DataItem[]> = ref([]);

const count = computed(() => dataSource.value.length + 1);
let editableData: any = reactive({});
const enableSave = ref(true);
let match: matchTable[] = [];
const getMatch = () => {
  match = [];
  dataSource.value.forEach((item) => {
    match.push({
      key: item.keyWord,
      matchType: item.matchType,
      value: item.valueWord,
    });
  });
};
// 编辑
const edit = (rid: string) => {
  editableData[rid] = cloneDeep(dataSource.value.filter((item) => rid === item.id)[0]);
  match = [];
};
// 保存
const save = (rid: string) => {
  if (editableData[rid].keyWord && editableData[rid].matchType && editableData[rid].valueWord) {
    Object.assign(dataSource.value.filter((item) => rid === item.id)[0], editableData[rid]);
    getMatch();
    delete editableData[rid];
  } else {
    message.warning('匹配数据均不能为空');
  }
};
// 删除
const onDelete = (rid: string) => {
  dataSource.value = dataSource.value.filter((item) => item.id !== rid);
  getMatch();
};
// 新增
const handleAdd = () => {
  let countStr = `${count.value}`;
  dataSource.value.forEach((item) => {
    if (item.id == countStr) {
      countStr = '1' + countStr;
    }
  });
  const newData: DataItem = {
    id: countStr,
    keyWord: '',
    matchType: '',
    valueWord: '',
    key: countStr,
  };
  dataSource.value.push(newData);
  editableData[newData.id] = newData;
};

const formState = reactive({
  ruleName: '',
  ruleDesc: '',
  routeLink: undefined,
  weight: undefined,
  ruleRelationship: '',
  checked: false,
  priority: undefined,
});

const title = ref('创建规则');
const visible = ref(false);
const routeLinkList = ref([]);

// 创建时获取所属链路
const getCreateData = async () => {
  routeLinkList.value = await getRouteLink();
};
const useCreate = async () => {
  title.value = '创建规则';
  visible.value = true;
  getCreateData();
};
const routeLinkRuleId = ref<number>();
// 处理抽屉数据
const computeMatchType = (matchTypeValue) => {
  let matchTypeLabel;
  if (matchTypeValue == 'exact') {
    matchTypeLabel = '精准匹配';
  } else if (matchTypeValue == 'regex') {
    matchTypeLabel = '正则匹配';
  } else if (matchTypeValue == 'contains') {
    matchTypeLabel = '包含';
  }
  return matchTypeLabel;
};
const routeLinkLabel = ref();
const handleEditDetailData = async (record) => {
  let res = await getRuleDetail(record.id);
  routeLinkRuleId.value = record.id;

  formState.ruleName = res.name;
  formState.ruleDesc = res.description;
  formState.routeLink = res.routeLinkKey;
  formState.weight = res.weight;
  formState.ruleRelationship = res.unionMode;
  formState.checked = res.status;
  formState.priority = res.priority;
  res.match.forEach(function (item, index) {
    item.keyWord = item.key;
    item.valueWord = item.value;
    item.id = `${index + 1}`;
    delete item.key;
    delete item.value;
  });
  routeLinkLabel.value = res.routeLinkName;
  dataSource.value = res.match;
  getMatch();
};
// 详情
const useDetail = (record) => {
  title.value = '规则详情';
  handleEditDetailData(record);

  visible.value = true;
};
// 编辑
const useEdit = async (record) => {
  title.value = '编辑规则';
  handleEditDetailData(record);
  visible.value = true;
};
// 关闭
const onClose = () => {
  formRef.value.clearValidate();
  editableData = {};
  visible.value = false;
  formState.ruleName = '';
  formState.ruleDesc = '';
  formState.routeLink = undefined;
  formState.weight = undefined;
  formState.ruleRelationship = '';
  formState.checked = false;
  formState.priority = undefined;
  dataSource.value = [];
};
// 提交
const emit = defineEmits(['getNewRecord']);
const submit = async () => {
  handleValidate().then(async () => {
    if (dataSource.value.length == 0) {
      match = [];
      message.warning('匹配数据均不能为空');
      return;
    } else if (JSON.stringify(editableData) !== '{}') {
      match = [];
      message.warning('未保存编辑数据');
      return;
    }
    let createEditParams = {
      description: formState.ruleDesc,
      match: match,
      name: formState.ruleName,
      priority: formState.priority,
      routeLinkKey: formState.routeLink.key,
      routeLinkName: formState.routeLink.label,
      routeLinkRuleId: routeLinkRuleId.value,
      status: formState.checked,
      unionMode: formState.ruleRelationship,
      weight: formState.weight,
    };
    if (title.value == '创建规则') {
      let res = await createRule(createEditParams);
      if (res) {
        message.success(res);
      }
    } else if (title.value == '编辑规则') {
      let res = await editRule(createEditParams);
      if (res) {
        message.success(res);
      }
    }
    emit('getNewRecord');
    onClose();
  });
};

const radioStyle = reactive({
  display: 'flex',
  height: '30px',
  lineHeight: '30px',
});
defineExpose({ useEdit, useDetail, useCreate });
</script>
<style scoped>
.editable-row-operations a {
  margin-right: 8px;
}
.btn-wrapper {
  display: flex;
  float: right;
}
</style>
